<template>


	<view class="container container-myVideos">
		<video ref='myVideo' id="myVideo" :controls="controls" :show-center-play-btn="false" :srcObject.prop="stream"
			autoplay></video>
		<!-- <button id="startRecordingButton" >开始录制</button> -->
		<!-- style="width: auto; height: 100%;" -->
		<!-- style="width:auto; height: 100%;"> -->
		<image :src="imgsrc"></image>
		<canvas id="canvas"> </canvas>
		<!-- <video id="recording" :src="spsrc" controls ></video> -->


		<view class="bt_foods">
			<view class="bt_foods_an">
				<view class="bt_time">
					{{minute}}:{{second}}
				</view>
				<view class="bt_start">

					<!-- <u-button type="primary" v-if="ispay" @click="clickstart">开始录制</u-button>
				   		<u-button type="error" v-if="!ispay" @click="clickstop">暂停录制</u-button> -->
				</view>

				<view class="bt_wc">
					{{success}}/{{maxsport}}
				</view>
			</view>
			<view class="bt_info" v-if="success<maxsport">
				<view class="bt_info_lable">
					@{{actionList.label}}
				</view>

				<view class="bt_info_content">
					<text>{{actionList.describe}}</text>
					<!-- <mp-html :content="actionList[success].describe"/> -->
				</view>

			</view>

		</view>

		<u-popup v-model="gameshow" mode="center" border-radius="35" @close="gameclose" :closeable="true"
			:overlay="true">
			<view class="fail-k">
				<view class="fail-title" v-if="link">
					活动结束感谢您的参与
				</view>
				<view class="fail-content" v-if="link">
					积分已到账，请注意查收
				</view>
				<view class="fail-title" v-if="!link">
					打卡成功，您已完成该项运动
				</view>
				<view class="fail-content" v-if="!link">

				</view>
				<view class="fail-bt-k" v-if="!link">

					<view class="fail-bt" @click="fhfun">
						返回
					</view>
				</view>
				<view class="fail-bt-k" v-if="link">
					<view class="fail-bt" @click="goshop">
						进入商城
					</view>
					<view class="fail-bt" @click="gohome">
						去首页
					</view>
				</view>

			</view>
		</u-popup>
		<u-popup v-model="failltkgameshow" mode="center" border-radius="35" @close="gameclose" :closeable="true"
			:overlay="true">
			<view class="fail-k">
				<view class="fail-title">
					活动结束感谢您的参与
				</view>
				<view class="fail-content">
					您未按照规定时间完成活动
				</view>
				<view class="fail-bt-k">
					<!-- <view class="fail-bt" @click="goshop">
											 		进入商城
											 	</view> -->
					<view class="fail-bt" @click="gohome">
						返回
					</view>
				</view>

			</view>
		</u-popup>
		<u-popup v-model="gameseecshow" mode="center" border-radius="35" @close="gametofun" :closeable="true"
			:overlay="true">
			<view class="fail-k" style="height: 300rpx;">
				<view class="fail-title">
					打卡成功
				</view>
				<!-- <view class="fail-content">
								 	恭喜你打卡成功，关闭或点击继续
								 </view>
								 <view class="fail-bt" @click="gametofun">
								 	继续
								 </view> -->
			</view>
		</u-popup>

		<u-popup v-model="sbshow" mode="center" border-radius="35" @close="closesb" :closeable="true" :overlay="true">
			<view class="fail-k">
				<view class="fail-title">
					提示
				</view>
				<view class="fail-content">
					未能识别到肢体动作，请重新上传
				</view>
				<view class="fail-bt" @click="gouplote">
					重新上传
				</view>
			</view>
		</u-popup>
	</view>



</template>

<script>
	// import uniWebview from '@dcloudio/vue-cli-plugin-uni/packages/uni-ui/lib/uni.webview.js';
	// import AuthorizationPopup from "@/components/AuthorizationPopup/index";
	// import { mapGetters } from "vuex";
	import {
		BASE_URL_IMAHE,
		BASE_URL
	} from "../../../utils/https";
	// import { getActivityDetails,beginActivity } from "@/api/index/index";
	// import { uploadVideo} from "@/api/upload/index";
	import {
		uploadVideo
	} from "@/api/upload/index";
	import {
		getActivityDetails,
		beginActivity,
		finishActivity,
		punchAction
	} from "@/api/index/index";

	var statusBarHeight = uni.getSystemInfoSync().statusBarHeight ? uni.getSystemInfoSync().statusBarHeight + "px" :
		"30rpx";


	let app = getApp();
	export default {
		name: "sportvideo",
		// computed: mapGetters(["isLogin"]),
		// components: {
		//   AuthorizationPopup,
		// },

		onLoad(options) {

			// var sjs=this.randomWord()
			//     var datatime = Date.parse(new Date());
			//     var tokens=''+sjs+''+datatime
			this.form.token = 0
			this.actiontoken = 0
			this.form.activityId = options.activityId
			this.form.whiteListId = options.whiteListId
			this.form.joinRecordId = options.joinRecordId
			this.form.actionId = options.actionId

			// if(uni.getStorageSync("type")=="chess"){
			this.form.userRef = uni.getStorageSync("userRef")
			// }
			// if(uni.getStorageSync("type")=="sport"){
			// 		  this.form.userRef=uni.getStorageSync("usersportRef")	
			// }
			this.getlist()



			// setInterval(()=>{
			//  this.success++
			// },1000)
		},


		onShow() {
			this.success = 0,
				setTimeout(() => {
					this.$nextTick(() => {
						// console.log("----")
						// this.info()
						this.startCamera(); // 页面加载完成后调用开始获取摄像头视频流函数
					})
					
					
				}, 1000)
			

		},
		deactivated() {
			// console.log("deactivated")
			clearInterval(this.setinterval)
			clearInterval(this.timeinterval)

		},
		data() {
			return {
				stream: null, // 存放视频流对象
				mediaRecorder: null,
				spsrc: "",
				videoElement: null,
				canvasElement: null,
				context: null,
				imgsrc: '',
				setinterval: null,
				timeinterval: null,
				ispay: true,
				minute: "00",
				second: "00",
				s: 0,
				f: 0,
				filelist: [],
				token: "",
				form: {},
				sbshow: false,
				gameshow: false,
				faillgameshow: false,
				failltkgameshow: false,
				gameseecshow: false,
				success: 0,
				actionList: [],
				maxsport: 0,
				link: '',
				tkTimeout: null,
				actionSetlist: [],
				actionindex: 0,
				controls: false,
				sportDuration: 0,
				actiontoken: "",


			};

		},
		//上拉s
		onReachBottom() {
			console.log("触发上拉加载");

		},
		methods: {
			fhfun() {
				uni.navigateBack(2)
			},
			gametofun() {
				this.gameseecshow = false
				// this.clickstart()
				clearTimeout(this.tkTimeout)
			},
			gameclose() {
				if (this.link) {
					uni.reLaunch({
						url: "/pages/home/index"
					})
				} else {
					uni.navigateBack(2);
				}

			},
			goshop() {
				window.location.href = this.link
			},
			gohome() {
				uni.reLaunch({
					url: "/pages/home/index"
				})
			},
			async getlist() {
				const res = await getActivityDetails(JSON.stringify({
					activityId: this.form.activityId,
					userRef: this.form.userRef
				}))
				console.log(res)
				if (res.result == 0) {
					this.actionSetlist = res.activity.actionSet.split(",")
					console.log(this.actionSetlist)
					// this.actionList=res.actionList


					res.actionList.forEach((item, index) => {
						if (item.id == this.form.actionId) {
							this.actionList = item
							this.maxsport = item.sportCount
							this.sportDuration = item.sportDuration
						}
					})

				}
			},

			clickstart() {


				// minute:"00",
				// second:"00",
				this.minute = this.f < 10 ? "0" + this.f : this.f
				this.second = this.s < 10 ? "0" + this.s : this.s
				var chunks = [];
				var that = this
				this.form.action = this.actionList.label
				this.mediaRecorder = new MediaRecorder(that.stream);

				this.mediaRecorder.ondataavailable = function(e) {
					chunks.push(e.data);
				};

				this.mediaRecorder.onstop = function() {
					var blob = new Blob(chunks, {
						type: "video/webm"
					});
					that.spsrc = URL.createObjectURL(blob);


				};
				this.timeinterval = setInterval(() => {
					if (this.sportDuration <= this.f) {
						this.clicktimestop()

					}
					this.s++


					if (this.s == 60) {
						this.f++
						if (this.f < 10) {
							this.minute = "0" + this.f
						} else {
							this.minute = this.f
						}
					}
					if (this.s == 60) {
						this.s = 0
					}
					if (this.s < 10) {
						this.second = "0" + this.s
					} else {
						this.second = this.s
					}


				}, 1000)

				this.mediaRecorder.start();
				this.ispay = false
				this.setinterval = setInterval(() => {


					if (this.filelist.length > 0) {
						// that.form.action=that.actionList[that.success].label
						uni.uploadFile({
							url: BASE_URL + '/uploadVideo', //仅为示例，非真实的接口地址
							files: that.filelist,
							// name: 'file',
							formData: that.form,
							success: (uploadFileRes) => {
								console.log(uploadFileRes)
								var rest = JSON.parse(uploadFileRes.data)
								if (rest.result == 0) {
									// uni.hideLoading()
									// that.gameshow=true
									// 
									if (this.faillgameshow) {
										return
									}
									if (this.success >= that.maxsport) {
										this.success = that.maxsport
									} else {
										// if(rest.action==this.actionSetlist[this.success]){
										//  this.success++
										//  this.actionindex=this.success
										// }
										if (this.actiontoken == rest.token) {
											this.success++
										}




									}


									// var sjs=that.randomWord()
									//     var datatime = Date.parse(new Date());
									//     var tokens=''+sjs+''+datatime
									// 	that.form.token=tokens
									if (that.success == that.maxsport) {

										that.finishActivityfun()
										that.clickstop()
									} else {
										if (that.actiontoken == rest.token) {
											that.actiontoken = that.success
											// that.gameseecshow = true
											that.form.token = that.success

											// that.clickstop()
											// that.tkTimeout = setTimeout(() => {
											// 	that.gameseecshow = false
											// }, 2000)
										}

									}

								} else {
									// var sjs=that.randomWord()
									//     var datatime = Date.parse(new Date());
									//     var tokens=''+sjs+''+datatime
									// 	that.form.token=tokens
									// that.actiontoken=tokens
								}
								// if(rest.result==-102){

								// 		uni.hideLoading()
								// 	var sjs=that.randomWord()
								// 	    var datatime = Date.parse(new Date());
								// 	    var tokens=''+sjs+''+datatime
								// 		that.form.token=tokens
								// 		that.sbshow=true
								// }


							},
							fail: (failres) => {
								uni.hideLoading()
								// var sjs=that.randomWord()
								//     var datatime = Date.parse(new Date());
								//     var tokens=''+sjs+''+datatime
								// 	that.token=tokens
								// that.actiontoken=tokens
							}
						});

						this.filelist = []

					} else {
						console.log(this.filelist)
					}
					that.savaimagefun()
				}, 2000)

			},
			clickstop() {
				clearInterval(this.setinterval)
				clearInterval(this.timeinterval)
				this.ispay = true
				this.mediaRecorder.stop();



			},
			clicktimestop() {
				clearInterval(this.setinterval)
				clearInterval(this.timeinterval)
				// this.ispay=true
				this.faillgameshow = true
				this.finishActivityfun()
				this.mediaRecorder.stop();



			},
			async finishActivityfun() {
				var sjs = this.randomWord()
				var datatime = Date.parse(new Date());
				var tokens = '' + sjs + '' + datatime
				this.form.token = tokens
				if (this.faillgameshow) {
					this.failltkgameshow = true
					this.form.result = "fail"
					return
				}
				delete this.form.action

				const res = await punchAction(JSON.stringify({
					activityId: this.form.activityId,
					whiteListId: this.form.whiteListId,
					joinRecordId: this.form.joinRecordId,
					userRef: this.form.userRef,
					actionId: this.form.actionId,
					token: this.form.token,
				}))
				if (res.result == 0) {
					this.gameshow = true
					// if(this.faillgameshow){
					// 	this.failltkgameshow=true
					// }else{

					// }


					this.link = res.jumpShopLink ? res.jumpShopLink : ""
				}
			},
			savaimagefun() {
				console.log(this.canvasElement.width, this.canvasElement.height)
				console.log("video", this.videoElement)
				this.context.drawImage(this.videoElement, 0, 0, this.canvasElement.width / 3, this.canvasElement.height /
					3);
				var src = this.canvasElement.toDataURL("image/png");
				this.imgsrc = src
				//调用
				var blob = this.dataURLtoBlob(this.imgsrc);
				var file = this.blobToFile(blob, new Date().getTime());
				var filetemp = URL.createObjectURL(blob)
				this.filelist.push({
					file: file
				})
				console.log(file, filetemp, blob, filetemp)
			},
			startCamera() {
				var that = this
				const constraints = {
					audio: true,
					video: true
				}; // 设置只需要视频流而不包含音频
				this.canvasElement = document.getElementById("canvas").children[0];
				this.context = this.canvasElement.getContext("2d");

				if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
					navigator.mediaDevices.getUserMedia({
							video: true
						})
						.then(function(stream) {
							that.stream = stream; // 将获取到的视频流赋值给data属性中的stream变量
							that.videoElement = document.getElementById("myVideo").children[0].children[0]
							that.videoElement.setAttribute("playsinline", true);
							that.videoElement.srcObject = stream
							// console.log()
							// 可选操作：如果想要自动播放视频流，则添加以下代码
							that.clickstart()

						})
						.catch((error) => {
							console.log("无法打开摄像头", error);
						});
				}
				
			
				
				
				
				

			},
			//将base64转换为blob
			dataURLtoBlob: function(dataurl) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			//将blob转换为file
			blobToFile: function(theBlob, fileName) {
				theBlob.lastModifiedDate = new Date();
				theBlob.name = fileName;
				return theBlob;
			},
			createTempFile(blob) {
				return URL.createObjectURL(blob);
			},
			randomWord() {
				var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
					'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
					'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
					'x', 'y', 'z'
				];
				var nums = "";
				for (var i = 0; i < 20; i++) {
					var id = parseInt(Math.random() * 61);
					nums += chars[id]
				}
				return nums;
			},

		},
	};
</script>

<style scoped lang="scss">
	.container {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background-color: #000000;
	}

	#canvas {
		position: absolute;
		width: 10%;
		height: 10vh;
		top: -200rpx;
	}

	#myVideo {
		width: 100%;
		height: 80vh;
	}

	#recording {
		position: absolute;
		width: 100%;
		height: 100vh;


	}

	#myVideo {
		position: absolute;
		z-index: 100;
	}

	//全屏按钮
	video::-webkit-media-controls-fullscreen-button {
		display: none;
	}

	//播放按钮
	video::-webkit-media-controls-play-button {
		display: none;
	}

	//进度条
	video::-webkit-media-controls-timeline {
		display: none;
	}

	//观看的当前时间
	video::-webkit-media-controls-current-time-display {
		display: none;
	}

	//剩余时间
	video::-webkit-media-controls-time-remaining-display {
		display: none;
	}

	//音量按钮
	video::-webkit-media-controls-mute-button {
		display: none;
	}

	video::-webkit-media-controls-toggle-closed-captions-button {
		display: none;
	}

	//音量的控制条
	video::-webkit-media-controls-volume-slider {
		display: none;
	}

	//所有控件
	video::-webkit-media-controls-enclosure {
		display: none;
	}


	.bt_foods {
		z-index: 101;
		width: 100%;
		box-sizing: border-box;

		position: fixed;
		padding: 10rpx 20rpx 50rpx;
		bottom: 0rpx;
		left: 0rpx;

		.bt_foods_an {

			display: flex;
			justify-content: space-between;
			width: 100%;
			align-items: center;

			.bt_time {
				padding: 10rpx 20rpx;
				background-color: #ffffff;
				color: #000;
				border-radius: 25rpx;
				font-size: 30rpx;
			}

			.bt_wc {
				padding: 10rpx 20rpx;
				background-color: #ffffff;
				color: #000;
				border-radius: 25rpx;
				font-size: 30rpx;
			}

		}

		.bt_info {
			font-size: 26rpx;
			color: #FFFFFF;
			max-height: 300rpx;
			overflow: hidden;
			overflow-y: auto;
			margin-bottom: 30rpx;

			.bt_info_lable {
				margin-top: 20rpx;
			}

			.bt_info_content {
				width: 100%;
				margin-top: 10rpx;

				// height: 5000rpx;


			}
		}

	}

	// 弹框
	.fail-k {
		width: 490rpx;
		height: 405rpx;
		text-align: center;

		.fail-title {
			padding-top: 120rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #111827;
		}

		.fail-content {
			margin-top: 29rpx;
			font-size: 24rpx;
			font-weight: bold;
			color: #718096;
		}

		.fail-bt {
			margin: 55rpx auto 0rpx;
			width: 328rpx;
			height: 64rpx;
			background-color: #292c34;
			color: #ffffff;
			border-radius: 35rpx;
			line-height: 64rpx;

		}

		.fail-bt-k {
			display: flex;
			justify-content: center;

			.fail-bt {
				margin: 55rpx auto 0rpx;
				width: 198rpx;
				height: 64rpx;
				background-color: #292c34;
				color: #ffffff;
				border-radius: 35rpx;
				line-height: 64rpx;

			}
		}

	}

	.jnshow-k {
		width: 650rpx;
		height: auto;
		padding-bottom: 40rpx;

		.jnshow-title {
			padding-top: 50rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #111827;
		}

		.jnshow-content {
			margin-top: 29rpx;
			font-size: 24rpx;
			font-weight: bold;
			color: #718096;
			padding: 0 20rpx;
			white-space: pre-wrap;
			text-align: left;
		}
	}

	.po-k {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		background-color: #FFFFFF;
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>